package com.heima.kafka.sample;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * 消息的消费者
 */
public class ConsumerFastStart {

    public static void main(String[] args) {
        //添加kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //消费者组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"group2");
        //消息的反序列化器
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");

        //消费者对象
        KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(properties);

        //订阅主题
        consumer.subscribe(Collections.singletonList("itheima-topic"));

        //当前线程一直处于监听状态
        while (true){
            //获取消息
            ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println(consumerRecord.offset());
                System.out.println(consumerRecord.key());
                System.out.println(consumerRecord.value());
            }
        }

    }

//    public static void main(String[] args) {
//
//
//        Properties properties = new Properties();
//        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
//        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"反编译器的全路径类名");
//        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"反编译器的全路径类名");
//        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"group1");  //组名 如果多个消费者 想要起到广播接收消息的作用 组名就不要一样
//
//
//        KafkaConsumer<String, String> KafkaConsumer = new KafkaConsumer<String, String>(properties);
//
//        KafkaConsumer.subscribe(Collections.singletonList("itheima-topic"));  //订阅该主题
//
//        //死循环 一直不听的监听
//        while (true){
//            ConsumerRecords<String, String> poll = KafkaConsumer.poll(Duration.ofMillis(1000));//每隔一秒接收一次消息
//            for (ConsumerRecord<String, String> p : poll) {
//                System.out.println(p.value());
//                System.out.println(p.key());
//                System.out.println(p.offset());//获取该主题的偏移量   意思是 数据是第一条 第一次接收就是1  第二次接收 就是2
//            }
//        }
//
//
//    }
}